package com.niit.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Date:2025/5/22
 * Author：Ys
 * Description:
 */
object StreamingWindow07 {

  def main(args: Array[String]): Unit = {
    val ssc = new StreamingContext(new SparkConf().setMaster("local[*]").setAppName("StreamingWindow07"), Seconds(3))
    ssc.sparkContext.setLogLevel("ERROR")
   ssc.checkpoint("cp1")
    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

    val wordOne: DStream[(String, Int)] = lines.flatMap(_.split(" ")).map((_, 1))

    //reduceByKeyAndWindow:当窗口范围比较大，但是滑块幅度比较小，那么可以才有增加数据和减少数据
    //反应数据实时的趋势
    val winDs: DStream[(String, Int)] = wordOne.reduceByKeyAndWindow(
      (x: Int, y: Int) => {
        x + y
      },
      (x: Int, y: Int) => {
        x - y
      },
      Seconds(9),
      Seconds(3)
    )
    //winDs.print()
    winDs.foreachRDD(rdd=>{
      // 在大项目当中，都是在foreachRDD 对数据库进行
      rdd.collect().foreach(println)
    })

    ssc.start()
    ssc.awaitTermination()

  }

}
